package org.kamionowski.supreme.interceptors;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * User: Marcin Kamionowski
 * Date: 06.04.11
 * Time: 01:54
 */
public class RequestTimeInterceptor extends HandlerInterceptorAdapter{

    private final static Log log = LogFactory.getLog(RequestTimeInterceptor.class);
    private final static String INTERCEPTOR = RequestTimeInterceptor.class.getName();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setAttribute(INTERCEPTOR, new Date());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        final Date start = (Date)request.getAttribute(INTERCEPTOR);
        final Date end = new Date();
        final long diff = end.getTime() - start.getTime();
        modelAndView.addObject("requestTime", diff);
    }
}
